package com.campus.secondhand.controller;

import java.security.Principal;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.campus.secondhand.common.Result;
import com.campus.secondhand.entity.User;
import com.campus.secondhand.model.vo.ProductListVO;
import com.campus.secondhand.model.vo.PurchaseRequestVO;
import com.campus.secondhand.service.FavoriteService;
import com.campus.secondhand.service.UserService;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 收藏控制器
 */
@RestController
@RequestMapping("/favorites")
@RequiredArgsConstructor
@Slf4j
public class FavoriteController {

    private final FavoriteService favoriteService;
    private final UserService userService;

    /**
     * 获取用户收藏商品列表
     *
     * @param principal 当前登录用户
     * @param page      页码
     * @param limit     每页数量
     * @param userId    用户ID
     * @return 收藏商品列表
     */
    @GetMapping("/products")
    @PreAuthorize("isAuthenticated()")
    public Result<Page<ProductListVO>> getUserFavoriteProducts(
            Principal principal,
            @RequestParam(required = false, defaultValue = "0") int page,
            @RequestParam(required = false, defaultValue = "10") int limit,
            @RequestParam(required = true) Long userId) {
        // 验证是否为合法请求
        Result<User> userResult = userService.getByUsername(principal.getName());
        if (userResult.getCode() != 200) {
            return Result.error(userResult.getCode(), userResult.getMessage());
        }

        // 验证用户是否存在
        User user = userService.getUserById(userId);
        if (user == null) {
            return Result.error(404, "用户不存在");
        }

        // 使用传入的userId参数
        Pageable pageable = PageRequest.of(page, limit);
        return favoriteService.getUserFavorites(userId, pageable);
    }

    /**
     * 获取用户收藏求购信息列表
     * 
     * @param principal 当前登录用户
     * @param userId    用户ID
     * @return 收藏求购信息列表
     */
    @GetMapping("/requests")
    @PreAuthorize("isAuthenticated()")
    public Result<Page<PurchaseRequestVO>> getUserFavoriteRequests(
            Principal principal,
            @RequestParam(required = true) Long userId) {
        // 验证是否为合法请求
        Result<User> userResult = userService.getByUsername(principal.getName());
        if (userResult.getCode() != 200) {
            return Result.error(userResult.getCode(), userResult.getMessage());
        }

        // 验证用户是否存在
        User user = userService.getUserById(userId);
        if (user == null) {
            return Result.error(404, "用户不存在");
        }

        // 不再使用分页参数，创建一个默认的分页对象
        Pageable pageable = PageRequest.of(0, Integer.MAX_VALUE);
        return favoriteService.getUserFavoritePurchaseRequests(userId, pageable);
    }
    

    /**
     * 添加商品收藏
     * 
     * @param principal 当前登录用户
     * @param productId 商品ID
     * @return 添加结果
     */
    @PostMapping("/products/{productId}")
    @PreAuthorize("isAuthenticated()")
    public Result<Void> addProductFavorite(
            Principal principal,
            @PathVariable Long productId) {

        Result<User> userResult = userService.getByUsername(principal.getName());
        if (userResult.getCode() != 200) {
            return Result.error(userResult.getCode(), userResult.getMessage());
        }

        return favoriteService.addFavorite(userResult.getData().getId(), productId);
    }

    /**
     * 添加求购信息收藏
     * 
     * @param principal         当前登录用户
     * @param purchaseRequestId 求购信息ID
     * @return 添加结果
     */
    @PostMapping("/requests/{purchaseRequestId}")
    @PreAuthorize("isAuthenticated()")
    public Result<Void> addRequestFavorite(
            Principal principal,
            @PathVariable Long purchaseRequestId) {

        Result<User> userResult = userService.getByUsername(principal.getName());
        if (userResult.getCode() != 200) {
            return Result.error(userResult.getCode(), userResult.getMessage());
        }

        return favoriteService.addPurchaseRequestFavorite(userResult.getData().getId(), purchaseRequestId);
    }

    /**
     * 添加商品收藏（兼容旧接口）
     */
    @PostMapping("/{productId}")
    @PreAuthorize("isAuthenticated()")
    public Result<Void> addFavorite(
            Principal principal,
            @PathVariable Long productId) {
        return addProductFavorite(principal, productId);
    }

    /**
     * 取消商品收藏
     * 
     * @param principal 当前登录用户
     * @param productId 商品ID
     * @return 取消结果
     */
    @DeleteMapping("/products/{productId}")
    @PreAuthorize("isAuthenticated()")
    public Result<Void> removeProductFavorite(
            Principal principal,
            @PathVariable Long productId) {

        Result<User> userResult = userService.getByUsername(principal.getName());
        if (userResult.getCode() != 200) {
            return Result.error(userResult.getCode(), userResult.getMessage());
        }

        return favoriteService.removeFavorite(userResult.getData().getId(), productId);
    }

    /**
     * 取消求购信息收藏
     * 
     * @param principal         当前登录用户
     * @param purchaseRequestId 求购信息ID
     * @return 取消结果
     */
    @DeleteMapping("/requests/{purchaseRequestId}")
    @PreAuthorize("isAuthenticated()")
    public Result<Void> removeRequestFavorite(
            Principal principal,
            @PathVariable Long purchaseRequestId) {

        Result<User> userResult = userService.getByUsername(principal.getName());
        if (userResult.getCode() != 200) {
            return Result.error(userResult.getCode(), userResult.getMessage());
        }

        return favoriteService.removePurchaseRequestFavorite(userResult.getData().getId(), purchaseRequestId);
    }

    /**
     * 取消商品收藏（兼容旧接口）
     */
    @DeleteMapping("/{productId}")
    @PreAuthorize("isAuthenticated()")
    public Result<Void> removeFavorite(
            Principal principal,
            @PathVariable Long productId) {
        return removeProductFavorite(principal, productId);
    }

    /**
     * 检查商品是否已收藏
     * 
     * @param principal 当前登录用户
     * @param productId 商品ID
     * @return 是否已收藏
     */
    @GetMapping("/products/{productId}/check")
    @PreAuthorize("isAuthenticated()")
    public Result<Boolean> checkProductFavorite(
            Principal principal,
            @PathVariable Long productId) {

        Result<User> userResult = userService.getByUsername(principal.getName());
        if (userResult.getCode() != 200) {
            return Result.error(userResult.getCode(), userResult.getMessage());
        }

        Boolean isFavorite = favoriteService.isFavorite(userResult.getData().getId(), productId);
        return Result.success(isFavorite, "获取成功");
    }

    /**
     * 检查求购信息是否已收藏
     * 
     * @param principal         当前登录用户
     * @param purchaseRequestId 求购信息ID
     * @return 是否已收藏
     */
    @GetMapping("/requests/{purchaseRequestId}/check")
    @PreAuthorize("isAuthenticated()")
    public Result<Boolean> checkRequestFavorite(
            Principal principal,
            @PathVariable Long purchaseRequestId) {

        Result<User> userResult = userService.getByUsername(principal.getName());
        if (userResult.getCode() != 200) {
            return Result.error(userResult.getCode(), userResult.getMessage());
        }

        Boolean isFavorite = favoriteService.isPurchaseRequestFavorite(userResult.getData().getId(), purchaseRequestId);
        return Result.success(isFavorite, "获取成功");
    }

    /**
     * 检查商品是否已收藏（兼容旧接口）
     */
    @GetMapping("/{productId}/check")
    @PreAuthorize("isAuthenticated()")
    public Result<Boolean> checkFavorite(
            Principal principal,
            @PathVariable Long productId) {
        return checkProductFavorite(principal, productId);
    }
}